<template>
    <z-paging
        ref="paging"
        :refresher-out-rate="0.8"
        :show-empty-view-reload-when-error="false"
        :empty-view-img-style="{ width: '308rpx', height: '308rpx' }"
        empty-view-error-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/1c53b8aed0c74201bb092265803a1d48.png"
        empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
        empty-view-error-text="暂无数据"
        safe-area-inset-bottom
        bg-color="#F5F8FE"
        v-model="dataList"
        @query="queryList"
    >
        <view slot="top" class="topTabbar">
            <u-tabs
                :current="currentTab"
                :list="tabList"
                @change="tabChange"
                :scrollable="false"
            ></u-tabs>
        </view>
        <view class="cellBox">
            <view class="flex_wrap fileBox" v-if="currentTab === 2"
                ><u-icon
                    label="转发记录"
                    size="50rpx"
                    name="file-text"
                    color="#666666"
                    @click="goTo"
                ></u-icon
            ></view>
            <view
                class="tongjiBox flex_wrap row_middle"
                v-if="[0, 1].includes(currentTab)"
            >
                <view>
                    <u--text
                        text="用户总数"
                        color="#fff"
                        size="24rpx"
                        align="center"
                        lineHeight="30"
                    ></u--text>
                    <u--text
                        :text="activeCount + activeNoCount || '0'"
                        size="36rpx"
                        color="#fff"
                        bold
                        align="center"
                    ></u--text>
                </view>
                <u-line direction="col" color="#0053B3" length="50%"></u-line>
                <view>
                    <u--text
                        text="已激活"
                        color="#fff"
                        size="24rpx"
                        align="center"
                        lineHeight="30"
                    ></u--text>
                    <u--text
                        :text="activeCount || '0'"
                        size="36rpx"
                        color="#fff"
                        bold
                        align="center"
                    ></u--text>
                </view>
                <view>
                    <u--text
                        text="未激活"
                        color="#fff"
                        size="24rpx"
                        align="center"
                        lineHeight="30"
                    ></u--text>
                    <u--text
                        :text="activeNoCount || '0'"
                        size="36rpx"
                        color="#fff"
                        bold
                        align="center"
                    ></u--text>
                </view>
            </view>

            <view class="detail" v-for="(item, index) in dataList" :key="index">
                <view
                    class="detail_title flex_wrap row_between row_middle"
                    v-if="currentTab === 0"
                    @click="
                        to_cardDetail(
                            item.cardNum,
                            item.maturityTime,
                            item.activationStatusContent
                        )
                    "
                >
                    <view class="flex_wrap row_middle">
                        <u-icon
                            :name="statusIcon[item.cardType]"
                            size="84rpx"
                        />
                        <view class="">
                            <u-text
                                :text="item.realName"
                                bold
                                size="36rpx"
                                color="#333"
                                margin="0 16rpx 20rpx 20rpx"
                            />
                            <view
                                class="flex_wrap row_between"
                                style="width: 550rpx"
                            >
                                <view
                                    ><u-text
                                        :text="
                                            `激活时间：` +
                                            `${
                                                item.activationTime &&
                                                item.activationTime.split(
                                                    'T'
                                                )[0]
                                            }`
                                        "
                                        size="28rpx"
                                        color="#666"
                                        margin="0 0 0 20rpx"
                                    />
                                </view>
                                <view>
                                    <u-text
                                        :text="item.cardPublicNum"
                                        size="28rpx"
                                        :color="statusBg[item.cardType]"
                                        align="right"
                                    />
                                </view>
                            </view>
                        </view>
                    </view>
                    <view
                        class="cardbg"
                        :style="{ background: statusBg[item.cardType] }"
                        >{{ item.cardType }}卡</view
                    >
                </view>
                <!-- 未激活 -->
                <view
                    class="detail_title1 flex_wrap row_between row_middle"
                    v-if="currentTab === 1"
                    @click="
                        to_cardDetail(
                            item.cardNum,
                            item.maturityTime,
                            item.activationStatusContent
                        )
                    "
                >
                    <view class="flex_wrap row_middle">
                        <u-icon
                            name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/20/93b270d00eee4c4191881bc6ad9b3c79.png"
                            size="84rpx"
                        />
                        <u-text
                            :text="`卡号：` + item.cardPublicNum"
                            bold
                            size="32rpx"
                            color="#333"
                            margin="0 16rpx 20rpx 20rpx"
                        />
                    </view>
                    <view
                        class="cardbg"
                        :style="{ background: statusBg[item.cardType] }"
                        >{{ item.cardType }}卡</view
                    >
                </view>
                <!-- 卡包 -->
				<view class="detail_title"  v-if="currentTab === 2">
					<view class="flex_wrap row_between row_middle">
						<u-text
							prefixIcon="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2024/03/26/69634380c6b14b678b6a0bf43c6a04ac.png"
							iconStyle="margin-right:16rpx;width:56rpx;height:56rpx" size="36rpx" color="#333" bold
							:text="item.ledName" />
						<view class="detail_title2_t">
							<text>剩余{{item.ledNumber || '0'}}张</text>
							<text>总数{{item.ledTotal || '0'}}张</text>
						</view>
					</view>
					<u-line dashed color="#CCCCCC" margin="20rpx 0 28rpx" />
					<view class="flex_wrap row_between row_bottom">
						<view>
							<u-text color="#777" size="28rpx"
								:text="`转发人：`+ (item.ledCouponManName || '-')" />
							<u-text color="#777" size="28rpx"
								:text="'开始时间：'+$u.timeFormat(item.ledCreateTime, 'yyyy-mm-dd')" margin="18rpx 0 0" />
						</view>
						<view class="flex_wrap">
							<view
							    class="btnBox1"
							    @click="QRcodeFun(item.ledId)"
							>
							    激活
							</view>
							<view
							    class="btnBox"
							    @click="
							        show = true;
							        idS = item.ledId;
							    "
							>
							    转发
							</view>
						</view>
					</view>
				</view>
            </view>
            <u-modal
                :show="show"
                ref="editModal"
                title="转发人手机号"
                showCancelButton
                @confirm="confirmEdit"
                @cancel="cancelEdit"
                confirmText="下一步"
                confirmColor="#1682FF"
            >
                <view slot="default" style="width: 100%">
                    <u--text
                        text="转发人手机号"
                        size="32rpx"
                        color="#3D3D3D"
                        lineHeight="80rpx"
                    ></u--text>
                    <u--input
                        type="number"
                        placeholder="请输入手机号"
                        :maxlength="11"
                        clearable
                        v-model="phoneNum"
                        :customStyle="{
                            background: '#F7F7F7',
                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
                            border: 'none',
                            height: '80rpx',
                        }"
                        :placeholderStyle="{
                            fontSize: '28rpx',
                            color: '#F7F7F7',
                        }"
                    ></u--input>
                </view>
            </u-modal>
            <u-modal
                :show="show1"
                ref="editModal"
                title="转发数量"
                showCancelButton
                @confirm="confirmEdit1"
                @cancel="cancelEdit1"
                confirmText="确定"
                confirmColor="#1682FF"
                cancelText="上一步"
            >
                <view slot="default" style="width: 100%">
                    <u--text
                        text="转发用户"
                        size="32rpx"
                        color="#3D3D3D"
                        lineHeight="80rpx"
                    ></u--text>
                    <u--input
                        v-model="userNamePhone"
                        disabled
                        :customStyle="{
                            background: '#F7F7F7',
                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
                            border: 'none',
                            height: '80rpx',
                        }"
                        :placeholderStyle="{
                            fontSize: '28rpx',
                            color: '#F7F7F7',
                        }"
                    ></u--input>
                    <u--text
                        text="转发数量"
                        size="32rpx"
                        color="#3D3D3D"
                        lineHeight="80rpx"
                    ></u--text>
                    <u--input
                        type="number"
                        placeholder="请输入转发数量"
                        :maxlength="11"
                        clearable
                        v-model="numBer"
                        :customStyle="{
                            background: '#F7F7F7',
                            borderRadius: '16rpx 16rpx 16rpx 16rpx',
                            border: 'none',
                            height: '80rpx',
                        }"
                        :placeholderStyle="{
                            fontSize: '28rpx',
                            color: '#F7F7F7',
                        }"
                    ></u--input>
                </view>
            </u-modal>
        </view>
        <view slot="bottom">
            <view class="bottom" v-if="[0, 1].includes(currentTab)">
                <u-button
                    text="+添加权益卡"
                    :customStyle="buttonCustomStyle"
                    shape="circle"
                    @click="Scanning_code"
                />
            </view>
        </view>
        <u-popup
            :show="showQR"
            :round="10"
            mode="center"
            @close="showQR = false"
            @touchmove.stop.prevent="() => {}"
        >
            <view class="QRWrap">
                激活权益卡二维码
                <u--image
                    :src="showImgData"
                    width="200px"
                    height="200px"
                ></u--image>
                长按保存或转发
            </view>
        </u-popup>
    </z-paging>
</template>

<script>
import { mapGetters } from "vuex";
import {
    addAgentAssociatedWithEquityCard,
    queryAgentAssociatedWithEquityCard,
    queryStatisticalDataWithEquityCard,
    genWxMpQrCode,
} from "@/api/cardSalesman";
import { cardPack } from "@/api/card";
import { userIdByPhone} from "@/api/enterprise.js"
import { favorableList ,transfer} from "@/api/coupon";
let customerId = "";
export default {
    data() {
        return {
            show: false,
            show1: false,
            idS: "",
            buttonCustomStyle: {
                height: "92rpx",
                width: "634rpx",
                backgroundColor: "#588BF3",
                fontSize: "36rpx",
                margin: "0 auto",
                color: "#FFF",
            },
            statusBg: {
                A: "#1682FF",
                B: "#14C9C9",
                C: "#FFB521",
                D: "#8F94ED",
                E: "#3AAB21",
            },
            statusIcon: {
                A: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/20/33ceb3883ccf4401b60336d5cc4597b3.png",
                B: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/11/02/ca78f64d06a647eeb1b12177acce9c4b.png",
                C: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/20/3346e7f0de044e0ab5e3bdc327b1e8a2.png",
                D: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/11/02/c22e5ad6130547ddad4f2e4c28b17f2b.png",
                E: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/11/02/d81e972b2665418f9c1613ca67569852.png",
            },
            tabList: [
                {
                    name: "已激活",
                    id: 0,
                },
                {
                    name: "未激活",
                    id: 1,
                },
                {
                    name: "卡包",
                    id: 2,
                },
            ],
            currentTab: 0,
            dataList: [],
            activeCount: "",
            activeNoCount: "",
            phoneNum: "",
            numBer: "",
            userNamePhone: "",
            showQR: false,
            showImgData: "",
        };
    },
    computed: {
        ...mapGetters(["isLogin", "phone"]),
    },
    methods: {
        cancelEdit() {
            this.phoneNum = "";
            this.show = false;
        },
        cancelEdit1() {
            this.show1 = false;
            this.numBer = "";
        },
        async confirmEdit1() {
            if (!this.numBer.trim().length || !/^[0-9]*$/.test(this.numBer))
                return uni.showToast({
                    title: "请输入数量",
                    icon: "none",
                });
            this.show1 = true;
            this.show = true;
            const params = {
                favorableLedId: this.idS,
                toUserId: customerId,
                number: this.numBer,
				source: 2,
				cardPackType : 2
            };
            let res = await transfer(params);
            if (res.code === 200) {
                uni.$u.toast(res.msg);
                this.cancelEdit();
                this.cancelEdit1();
                this.$refs.paging.reload();
            }
        },
        QRcodeFun(ledId) {
            this.showQR = true;
            const params = {
                scene: 5,
                sceneId:ledId,
            };
            genWxMpQrCode(params).then((res) => {
                if (res.code === 200 && res.data) {
                    this.showImgData = res.data.qrCodeUrl;
                }
            });
        },
        async confirmEdit() {
            if (
                !this.phoneNum.trim().length ||
                !/^1[3456789]\d{9}$/.test(this.phoneNum)
            )
                return uni.showToast({
                    title: "请输入正确的手机号",
                    icon: "none",
                });
            let { code, data } = await userIdByPhone({
                phone: this.phoneNum,
            });
            if (code === 200 && data) {
                console.log("data :>> ", data);
                customerId = data.id;
                this.userNamePhone = `${data?.nickName ?? "微信用户"}  ${
                    data.mobile
                }`;
                this.show1 = true;
            } else {
                uni.showToast({
                    title: "请输入正确的手机号",
                    icon: "none",
                });
            }
        },
        getQueryString(url, name) {
            let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            let r = url.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        },
        Scanning_code() {
            const that = this;
            uni.scanCode({
                onlyFromCamera: false,
                success(res) {
                    console.log("res :>> ", res);
                    let cardNum = res?.result;
                    if (res.scanType === "QR_CODE") {
                        console.log(
                            "params :>> 扫码的",
                            that.getQueryString(res?.result, "card")
                        );
                        cardNum = that.getQueryString(res?.result, "card");
                    }
                    addAgentAssociatedWithEquityCard({
                        cardsSet: [cardNum],
                    }).then((v) => {
                        if (v.code === 200) {
                            console.log(v);
                            uni.$u.toast(v.data);
                            setTimeout(() => {
                                that.$refs.paging.reload();
                            }, 500);
                        } else {
                            uni.$u.toast(v.msg);
                        }
                    });
                },
            });
        },
        async queryList(pageNo, pageSize) {
            const that = this;
            let result;
            switch (this.currentTab) {
                case 0:
                case 1:
                    let params1 = {
                        pageNum: pageNo,
                        pageSize: pageSize,
                        salesmanId: this.$store.getters?.userInfo.id,
                        activationStatus: this.currentTab ? "0" : "1",
                    };
                    this.getQueryStatisticalDataWithEquityCard();
                    result = await queryAgentAssociatedWithEquityCard(params1);
                    break;
                case 2:
                    const params2 = {
                        pageNum: pageNo,
                        pageSize: pageSize,
						cardPackType : 2
                    };
                    result = await favorableList(params2);
            }
            that.$refs.paging.completeByTotal(this.currentTab == 2 ? result.data.rows : result.data, result.total);
        },
        async getQueryStatisticalDataWithEquityCard() {
            //获取卡人数
            const res = await queryStatisticalDataWithEquityCard();
            if (res.data.length) {
                if (
                    res.data.length == 1 &&
                    res.data[0].status_description == "已激活"
                ) {
                    this.activeCount = res.data[0].count;
                } else if (
                    res.data.length == 1 &&
                    res.data[0].status_description == "未激活"
                ) {
                    this.activeNoCount = res.data[0].count;
                } else {
                    this.activeNoCount = res.data[0].count;
                    this.activeCount = res.data[1].count;
                }
            }
        },
        async tabChange(e) {
            this.currentTab = e.index;
            await this.$refs.paging.reload();
        },

        to_cardDetail(cardNum, maturityTime, activationStatusContent) {
            if (activationStatusContent === "未激活")
                return uni.$u.toast(activationStatusContent);
            uni.$u.route({
                url: "/pages_my/user_manage/cardList/detail",
                params: {
                    cardNum: cardNum,
                    maturityTime: maturityTime,
                },
            });
        },
        goTo() {
            uni.$u.route({
                url: "/pages_benefitCard/my_beneifitCard/record",
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.topTabbar {
    background-color: #fff;
    padding-bottom: 16rpx;
}
.scanLine {
    width: 0rpx;
    height: 26rpx;
    border: 2rpx solid #d8d8d8;
}
.fileBox {
    justify-content: flex-end;
    padding: 30rpx 20rpx 0 0;
}
.cellBox {
    width: 92vw;
    margin: 0 auto;

    ::v-deep .u-cell {
        box-shadow: 0 0 12rpx 2rpx rgba(0, 0, 0, 0.08);
        margin-top: 32rpx;
        border-radius: 20upx;
    }

    ::v-deep .u-cell__body {
    }
}
.detail {
    width: 100%;
    box-sizing: border-box;
    border-radius: 20rpx;
    margin-top: 32rpx;
    background: #ffffff;

    &_title {
        width: 100%;
        padding: 26rpx 28rpx;
        box-sizing: border-box;
        position: relative;
    }
   &_title1 {
       width: 100%;
       padding: 18rpx;
       box-sizing: border-box;
       position: relative;
   }
   &_title2_t {
	   font-size: 28rpx;
	   text{
	   			   margin-left: 12rpx;
	   }
   }
}
.cardbg {
    position: absolute;
    top: 0rpx;
    right: 0rpx;
    width: 120rpx;
    border-radius: 0rpx 28rpx 0 28rpx;
    height: 48rpx;
    text-align: center;
    line-height: 48rpx;
    font-size: 36rpx;
    color: #ffffff;
}
.scanning_code {
    width: 144rpx;
    padding-right: 52rpx;
}

.btnBox {
    background: #1682ff;
    border-radius: 28rpx 28rpx 28rpx 28rpx;
    color: #ffffff;
    font-size: 26rpx;
    padding: 4rpx 30rpx;
}
.btnBox1 {
    border: 1rpx solid #1682ff;
    border-radius: 28rpx 28rpx 28rpx 28rpx;
    color: #1682ff;
    font-size: 26rpx;
    padding: 4rpx 30rpx;
    margin-right: 10rpx;
}
.QRWrap {
    text-align: center;
    padding-top: 40rpx;
}
.bottom {
    width: 100%;
    height: 160rpx;
    padding-top: 16rpx;
    background-color: #fff;
}
.tongjiBox {
    width: 100%;
    height: 170rpx;
    background: url("https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/24/ce9404cf4ba14c1499d63c41543944a9.png")
        no-repeat;
    background-size: contain;
    view {
        flex: 1;
    }
}
</style>
